// watermark.js
export function init(text, options) {
	let width = 500;
	// #ifdef H5
	width = screen.width
	doWatermark(text + formatDate(new Date()), options, width);
	// #endif

	// #ifdef APP-PLUS	
	uni.getSystemInfo({
		success: function(info) {
			console.log('屏幕宽度：' + info.windowWidth);
			// 你可以将屏幕宽度保存在一个变量中供后续使用
			doWatermark(text, options, info.windowWidth);
		}
	});
	// #endif
}

function formatDate(date) {
	const day = date.getDate().toString().padStart(2, '0');
	const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
	const year = date.getFullYear();
	const hours = date.getHours().toString().padStart(2, '0');
	const minutes = date.getMinutes().toString().padStart(2, '0');
	const seconds = date.getSeconds().toString().padStart(2, '0');

	// return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	return `${year}-${month}-${day}`;
}

function doWatermark(text, options, width) {
	let {
		alpha,
		fontSize,
		color,
		rotate,
		zIndex,
		w,
		h
	} = options;

	if (!w)
		w = 150;
	if (!h)
		h = 150;
	let row = Math.floor(width / uni.upx2px(50));
	let col = 2;
	for (let i = 0; i < row; i++) {
		for (let j = 0; j < col; j++) {
			const watermarker = _createWatermark(text, {
				alpha,
				fontSize,
				color,
				rotate,
				zIndex,
				w,
				h,
				row: i,
				col: j,
			});
			document.body.appendChild(watermarker);
		}
	}
}

function _createWatermark(text, options) {
	// 只能用于 h5
	const div = document.createElement('div');
	div.style.pointerEvents = 'none';
	div.style.position = 'fixed';
	div.style.top = (options.row * options.h + 80) + 'px';
	div.style.left = (options.col * options.w + 20) + 'px';
	div.style.zIndex = options.zIndex;
	div.style.transform = `rotate(${options.rotate}deg)`;
	div.style.opacity = options.alpha;
	div.style.fontSize = `${options.fontSize}px`;
	div.style.color = options.color;
	div.style.whiteSpace = 'nowrap';
	div.innerHTML = text;
	return div;
}

export function addWatermark(page) {
	const ctx = uni.createCanvasContext('myCanvas', page);
	// 加载背景图片
	// ctx.drawImage('/static/bg.jpg', 0, 0, 200, 200);
	// 设置水印文字
	ctx.setFontSize(20);
	ctx.setFillStyle('red');
	ctx.setGlobalAlpha(0.5);
	// 绘制水印文字
	ctx.fillText('WATERMARK', 20, 100);
	ctx.draw(false, () => {
		uni.canvasToTempFilePath({
			canvasId: 'myCanvas',
			success: (res) => {
				this.watermarkedImage = res.tempFilePath;
			},
			fail: (err) => {
				console.error(err);
			}
		});
	});
}